package de.homelabs.web.sandbox.webapp2.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import de.homelabs.moonrat.exception.MoonratException;
import de.homelabs.moonrat.page.MoonratPageManager;
import de.homelabs.moonrat.template.MoonratMenuItem;

@Controller
public class FrontController {

	Logger logger = Logger.getLogger(FrontController.class);
	
	@Autowired 
	MoonratPageManager mPageManager; 

	@RequestMapping({ "*.css", "*.js" })
	protected void handleMediaRequest(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws IOException, NamingException, MoonratException {
		System.out.println("sp:"+request.getPathInfo());
		File file = mPageManager.getMediaFile(request);
		if (request.getServletPath().contains(".css")) {
			response.setContentType("text/css");
		} else if (request.getServletPath().contains(".js")) {
			response.setContentType("text/javascript");
		}
		response.setContentLength((int) file.length());
		//read file and copy to browser request
		OutputStream os = response.getOutputStream();
		IOUtils.copy(new FileInputStream(file), os);
	}
	
	@RequestMapping("/**")
	protected ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws IOException, NamingException {
			
		/**
		 * Step 1
		 * Simple output with the internal debug page
		 */
		//return mPageManger.getDebugPage(request, response);
		
		/**
		 * Step 2
		 * lets handle freemarker the view part
		 */
//		Map<String, Object> model = new HashMap<String, Object>();
//		model.put("content", "Welcome to Step2!");
//		return new ModelAndView("step2.html", model);
		
		/**
		 * Step 3
		 * freemarker redirected to moonrat - our goal
		 */
		if (request.getRequestURI().equalsIgnoreCase(request.getContextPath())){
			//redirect
			return new ModelAndView(new RedirectView("index.html"));
		} else {
			return mPageManager.handlePageRequest(request, response, map);
		}
	}
}
